import { IPublisher, EnterOptionParser } from "../IPublisher";

export class TTPublisher extends IPublisher {
    protected _tt:any;
    private _appInfo:{version:string, appId:string};
    initSDK(caller?: any, onSuccess?: Function, onFail?: Function): void {
        this._tt = window['tt'];
        super.initSDK(caller, onSuccess, onFail);
    }

    get appVersion(): string {
        this._setAppInfo();
        return this._appInfo.version;
    }

    private _setAppInfo():void {
        if (this._appInfo) {
            return;
        }
        if (this._tt.getEnvInfoSync) {
            let info = this._tt.getEnvInfoSync();
            this._appInfo = {
                appId: info.microapp.appId,
                version: info.microapp.mpVersion,
            }
        }
        else if (this._tt.getLaunchOptionsSync) {
            let options = this._tt.getLaunchOptionsSync();
            this._appInfo = {
                appId: options.extra.appId,
                version: options.extra.mpVersion,
            }
        }
        else {
            this._appInfo = {
                appId: "宿主版本过低",
                version: "宿主版本过低"
            }
        }
    }
    
    get appId(): string {
        this._setAppInfo();
        return this._appInfo.appId;
    }

    protected _initEnterOptions(info?:any): EnterOptionParser {
        if (info) {
            return this._enterOptions = new EnterOptionParser(info);
        }
        if (this._tt.getLaunchOptionsSync) {
            return this._enterOptions = new EnterOptionParser(this._tt.getLaunchOptionsSync());
        }
        return this._enterOptions = new EnterOptionParser("");
    }

    showView(viewName: string, caller?: any, onClose?: Function): void {
        if(viewName == "sidebar") {
            this._tt && this._tt.navigateToScene && this._tt.navigateToScene({scene:viewName})
        }
    }

    async subscribeMessage(subscribeMsgIds:string[]):Promise<boolean> {
        return this._subscribeMessage(subscribeMsgIds, this._tt);
    }
    
    onError(call:(...error:any[])=>void):void {
        this._tt && this._tt.onError && this._tt.onError(call);
    }

    offError(call:(...error:any[])=>void):void {
        this._tt && this._tt.offError && this._tt.offError(call);
    }
}
